using System.ComponentModel.DataAnnotations.Schema;
using UniversalAdmin.Domain.Common;
using UniversalAdmin.Domain.Enums;
using UniversalAdmin.Domain.Events;

namespace UniversalAdmin.Domain.Entities;

[Table("articles")]
public class Article : AggregateRoot
{
  public string Title { get; private set; } = null!;
  public string Content { get; private set; } = string.Empty;
  public string Summary { get; private set; } = string.Empty;
  public ArticleStatus Status { get; private set; } = ArticleStatus.Draft;
  public int? CategoryId { get; private set; }
  public int UserId { get; private set; }

  // 导航属性
  public virtual ArticleCategory? Category { get; private set; }
  public virtual User? User { get; private set; }


  private Article() { } // EF Core 需要

  /// <summary>
  /// 工厂方法：创建新文章
  /// </summary>
  public static Article Create(string title, string content, string summary, int userId, ArticleStatus status, int? categoryId = null)
  {
    var article = new Article
    {
      Title = title,
      Content = content,
      Summary = summary,
      UserId = userId,
      CategoryId = categoryId,
      Status = status
    };

    // 发布领域事件
    article.AddDomainEvent(new ArticleCreatedEvent(article));

    return article;
  }

  /// <summary>
  /// 发布文章
  /// </summary>
  public void Publish()
  {
    if (Status != ArticleStatus.Draft)
      throw new InvalidOperationException("只有草稿状态的文章才能发布");

    Status = ArticleStatus.Published;
    AddDomainEvent(new ArticlePublishedEvent(this));
  }

  /// <summary>
  /// 归档文章
  /// </summary>
  public void Archive()
  {
    if (Status != ArticleStatus.Published)
      throw new InvalidOperationException("只有已发布的文章才能归档");

    Status = ArticleStatus.Archived;
    AddDomainEvent(new ArticleArchivedEvent(this));
  }

  /// <summary>
  /// 更新文章内容
  /// </summary>
  public void UpdateContent(string title, string content, string summary, int? categoryId,ArticleStatus status)
  {
    Title = title;
    Content = content;
    Summary = summary;
    CategoryId = categoryId;
    UpdatedAt = DateTime.UtcNow;
    Status=status;

    AddDomainEvent(new ArticleUpdatedEvent(this));
  }

  /// <summary>
  /// 判断当前用户是否有权限编辑或删除文章
  /// </summary>
  public bool CanEditOrDelete(int currentUserId, IEnumerable<string> currentUserRoles)
  {
    // 超级管理员和管理员可以操作任何人的文章
    if (currentUserRoles.Contains("SuperAdmin") || currentUserRoles.Contains("Admin"))
      return true;

    // 普通用户只能操作自己的文章
    return UserId == currentUserId;
  }
}